/* $RCSFile: CrmInputContact.ascx.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/AddonNice/PageModules/CrmInputContact/CrmInputContact.ascx.cs $
 * $log$
 * Revision 20 2010/08/09 10:51:19  christian.surieux
 *   Added Log comment to all .aspx .ascx .master files
 * Revision 19 2010/08/09 09:43:49  christian.surieux
 *   Added Log to cs sources files
 * Revision 6 2010/08/06 19:56:24  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;  
using System.Web.UI.WebControls;
using System.Diagnostics;
using System.Drawing;
using System.Data.SqlClient;
using System.Web.Services.Protocols;
using System.Globalization;

using AddonNice.UI;
using AddonNice.Design;
using AddonNice.UI.WebControls;
using AddonNice.Security;
using AddonNice.UI.DataTypes;
using AddonNice.Configuration;
using AddonNice.Configuration.Settings;
using AddonNice.Diagnostics;
using AddonNice.Helpers;
using AddonNice.Settings;

using AddonNice.CRMWrapper;
using CrmSdk;

using Trace2    =   System.Diagnostics.Trace;

namespace AddonNice.PageModules.CrmInputContact
{
    public class AStr
    {
        public const string EmailMandatory       = "CONTACT_INPUT_EMAIL";
        public const string AddressMandatory     = "CONTACT_INPUT_ADDRESS";
        public const string CrmInputContactOwner = "CONTACT_INPUT_OWNER";
        public const string AutoCreateCompany    = "CONTACT_INPUT_CREATE_COMPANY";
        public const string AssignToOwner        = "CONTACT_INPUT_OWNER_ATTRIBUTE";
    }

    /// <summary>
    /// Initializer class for CrmInputContact 
    /// </summary>
    public class CrmInputContactSI : PortalCRMModuleControlSI
    {
        public CrmInputContactSI(ModuleSettingsDictionary bSettings,ISettingsOwner pm) : base()
        {
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmInputContactSI Ctor BEG.",ModuleTraceSwitch.Sw.Info);
            InitSettings(bSettings,pm);
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmInputContactSI Ctor END.",ModuleTraceSwitch.Sw.Info);
        }
 
        public override void InitSettings(ModuleSettingsDictionary bSettings,ISettingsOwner pm)
        {             
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmInputContactSI InitSettings BEG.",ModuleTraceSwitch.Sw.Info);
            
            base.InitSettings(bSettings,pm);


			// Specific parameters
			const string resFile	                =	"CrmInputContact";
            string extgrp                           =   pm.ExtendedResourcesGroup;

            SettingItemSpecial AttributeOwner       =   new SettingItemSpecial(AStr.AssignToOwner,new BooleanDataType());
            AttributeOwner.Required                 =   false;
			AttributeOwner.ResourceFile             =   resFile;
            AttributeOwner.Value                    =   "False";
            AttributeOwner.Order                    =   10;
            AttributeOwner.ExtendedGroupName        =   extgrp;
            AttributeOwner.EnglishName              =   "Assign to Owner";
            AttributeOwner.Description              =   "When checked, the new crm contact will be automatically assigned to selected owner";
            bSettings.AddSetting(AttributeOwner);

            WSListDataType defAcc                   =   new WSListDataType(CrmStr.systemuser,"name", "ID");
            SettingItemSpecial ModuleOwner          =   new SettingItemSpecial(AStr.CrmInputContactOwner,defAcc);
            // default == CRMDefaultAccount or first
            ADNDynSystemUser wsys                   =   null;
            if (!string.IsNullOrEmpty(Config.CRMDefaultAccount))
            {
                string domainName                   =   string.Format("{0}\\{1}",Config.CRMDefaultAccountDomain,Config.CRMDefaultAccount);
                wsys                                =   Wrapper.Util.FindSystemUserByDomainName(domainName);
            }
            else 
            {
                wsys                                =   DynEntity.GetFromCache<ADNDynSystemUser>(CrmStr.systemuser,Wrapper,new ResetWrapperHandler(ResetWrapper),Wrapper.adminUserId);
            }
            if (wsys != null)
            {
                ModuleOwner.Value                   =   wsys.systemuserid.ToString();
                defAcc.DisplayTextValue             =   wsys.fullname;
            }
            ModuleOwner.EnglishName                 =   "Owner";
            ModuleOwner.ResourceFile                =   resFile;
            ModuleOwner.Order                       =   20;
            ModuleOwner.ExtendedGroupName           =   extgrp;
            ModuleOwner.Description                 =   "Choose the owner for contacts created with this module if specified by previous ckeckbox";
            ModuleOwner.SettingItemsEvent           +=  new SettingItemsEventHandler(ModuleOwner_SettingItemsEvent);
            bSettings.AddSetting(ModuleOwner);

            // Need Email for this Contact 
            SettingItemSpecial EmailMandatory       =   new SettingItemSpecial(AStr.EmailMandatory,new BooleanDataType());
            EmailMandatory.Required                 =   false;
            EmailMandatory.ResourceFile             =   resFile;  
            EmailMandatory.Value                    =   "False";
            EmailMandatory.Order                    =   30;
            EmailMandatory.ExtendedGroupName        =   extgrp;
            EmailMandatory.EnglishName              =   "Email needed ";
            EmailMandatory.Description              =   "When checked email is required for new contact";
            bSettings.AddSetting(EmailMandatory);

            //  Need Adresse for this Contact
            SettingItemSpecial AddressMandatory     =   new SettingItemSpecial(AStr.AddressMandatory,new BooleanDataType());
            AddressMandatory.Required               =   false;
            AddressMandatory.ResourceFile           =   resFile;
            AddressMandatory.Value                  =   "False";
            AddressMandatory.Order                  =   40;
            AddressMandatory.ExtendedGroupName      =   extgrp;
            AddressMandatory.EnglishName            =   "Address needed";
            AddressMandatory.Description            =   "When checked Address fields are required for this contact";
            bSettings.AddSetting(AddressMandatory);

            // to create the nonexisting companies automatically
            SettingItemSpecial AutoCreateCompany    =   new SettingItemSpecial(AStr.AutoCreateCompany,new BooleanDataType());
            AutoCreateCompany.Required              =   false;
            AutoCreateCompany.ResourceFile          =   resFile;
            AutoCreateCompany.Value                 =   "False";
            AutoCreateCompany.Order                 =   50;
            AutoCreateCompany.ExtendedGroupName     =   extgrp;
            AutoCreateCompany.EnglishName           =   "Create account";
            AutoCreateCompany.Description           =   "When checked the nonexisting companies are automatically created, else the company name is lost";
            bSettings.AddSetting(AutoCreateCompany);
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmInputContactSI InitSettings END.",ModuleTraceSwitch.Sw.Info);
        }
        
        /// <summary>
        /// Used to set the good display value in ModuleOwner when loaded from DB
        /// </summary>
        void ModuleOwner_SettingItemsEvent(object sender, SettingItemsEventArgs e)
        {
            if ( e.EventType != SettingItemsEventType.Loaded )
                return;
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmInputContactSI ModuleOwner_SettingItemsEvent Guid: {0}", e.Data),ModuleTraceSwitch.Sw.Info);
            Guid custId             =   new Guid((string)e.Data);
            if ( custId == Guid.Empty )
                return;
            ADNDynSystemUser dynac  =    DynEntity.GetFromCache<ADNDynSystemUser>(CrmStr.systemuser,Wrapper,new ResetWrapperHandler(ResetWrapper),custId);
            WSListDataType defAcc   =   (WSListDataType )((SettingItem)sender).DataType;
            defAcc.DisplayTextValue =   dynac.fullname;
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmInputContactSI ModuleOwner_SettingItemsEvent END name: {0}", dynac.name),ModuleTraceSwitch.Sw.Info);
        }
    
    }

    public partial class CrmInputContact : PortalCRMModuleControl
    {
        
        AddonNiceUserDB userDB  = new AddonNiceUserDB();

        #region General implementation

        public override Guid GuidID
        {
            get
            {
                return new Guid("{3A37C119-03A6-4ea1-8D46-44E0746B158A}");
            }
        }
        #endregion General implementation

        /// <summary>
        /// constructor
        /// </summary>
        public CrmInputContact()
        {
            // Validators : name Ok
            ValidationGroup                         =   "Main";
        }

        public override string ExtendedResourcesGroup 
		{
            get
            {
                const string extgrp                     =   "INPUTCRMCONTACT";
                return extgrp;
            }
		}

        public override void InitPortalModuleControl(ModuleSettingsDictionary bSettings)
        {
            PortalModuleInitializer =   new CrmInputContactSI(bSettings,this);
        }

        
        protected void Page_Load(object sender, EventArgs e)
        {
            if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmInputContact Page_Load isPostBack: {0}",IsPostBack),ModuleTraceSwitch.Sw.Info);
            if (!IsPostBack)
            {
                SqlDataReader rd = null;
                try
                {
                    rd = userDB.GetAllCivilities();
                    RadDDLCivilite1.DataTextField   = "CiviliteTxt";
                    RadDDLCivilite1.DataValueField  = "CiviliteId";
                    RadDDLCivilite1.DataSource = rd;
                    RadDDLCivilite1.DataBind();
                }
                catch (Exception ex)
                {
                    if (ModuleTraceSwitch.Sw.TraceError)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CrmInputContact Page_Load GetAllCivilities ex: {0}", ex),ModuleTraceSwitch.Sw.Info);
                    throw;
                }
                finally
                {
                    if (rd != null && !rd.IsClosed )
                        rd.Close();
                }
                lblLastname.ForeColor           =   Color.Red;
                Style nst                       =   new Style();
                nst.ForeColor                   =   Color.Red;
                // If email field is mandatory, we set a validator on it
                if (Settings[AStr.EmailMandatory].ToBool())
                {
                    RFVEmail.Enabled            = true;
                    lblEmailaddress1.ApplyStyle(nst);
                }
                if (Settings[AStr.AddressMandatory].ToBool())
                {
                    RFVAddress.Enabled          = true;
                    lblAdress1_name.ApplyStyle(nst);

                    REVCodePostale.Enabled              = true;
                    lblAddress1_postalcode.ApplyStyle(nst);

                    REVCity.Enabled                     = true;
                    lblAddress1_city.ApplyStyle(nst);

                    REVCountry.Enabled                  = true;
                    lblAddress1_country.ApplyStyle(nst);
                }
                else
                {
                    RFVAddress.Enabled                  = false;
                    REVCodePostale.Enabled              = false;
                    REVCity.Enabled                     = false;
                    REVCountry.Enabled                  = false;
                }
            }
        }

        /// <summary>
        /// Tasks to do:
        /// 0) validate datas
        /// 1) Insert record in CRM
        /// </summary>
        void CrmInputContact_ADNUpdateModule(object sender, ModuleEventArgs e)
        {
            // Should Email contain values
            if (Settings[AStr.EmailMandatory].ToBool())
                Page.Validate("Email");
            // Should Address contain values
            if (Settings[AStr.AddressMandatory].ToBool())
                Page.Validate("Address");
            if (!Page.IsValid)
            {
                if (ModuleTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmInputContact CrmInputContact_ADNUpdateModule : Page not valid"),ModuleTraceSwitch.Sw.Info);
                return;
            }
            Guid CrmAccountId           = Guid.Empty;
            // If the Company Name is empty checks the existence of the company
            string searchedCompany      =   RadtxtCompanyName.Text.Trim();
            bool accountCreated         =   false;
            if ( searchedCompany != string.Empty )
            {
                ADNDynAccount s          =   Wrapper.Util.FindAccountByName(searchedCompany,Settings[AStr.AutoCreateCompany].ToBool(),ref accountCreated);
                if ( s != null )
                    CrmAccountId        =    s.accountid;
            }
			// Add new CRMContact to the database
            try
            {
                string fullname         =   Wrapper.MakeFullName(RadtxtFirstname.Text.Trim(),RadtxtLastname.Text.Trim(),string.Empty);
                
                ADNDynContact im         =   new ADNDynContact(Wrapper,RadtxtFirstname.Text.Trim(),RadtxtLastname.Text.Trim());
                im.SetOwnerFromUserId();
                im.emailaddress1        =   RadtxtEmailaddress1.Text.Trim();
                im.address1_line1       =   RadtxtAddress1_line1.Text.Trim();
                im.address1_line2       =   Radtxtaddress1_line2.Text.Trim();
                im.address1_line3       =   Radtxtaddress1_line3.Text.Trim();
                im.firstname            =   RadtxtFirstname.Text.Trim();
                im.lastname             =   RadtxtLastname.Text.Trim();
                im.address1_city        =   RadtxtAddress1_city.Text.Trim();
                im.address1_country     =   RadtxtAddress1_country.Text.Trim();
                im.address1_county      =   RadtxtAddress1_county.Text.Trim();
                im.address1_postalcode  =   RadtxtAddress1_postalcode.Text.Trim();
                im.telephone1           =   RadtxtAddress1_telephone1.Text.Trim();
                im.fax                  =   RadtxtFax.Text.Trim();
                im.description          =   RadTextSubject.Text.Trim();

                if (CrmAccountId != Guid.Empty)
                {
                    if (ModuleTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"V]CrmInputContact CrmInputContact_ADNUpdateModule CrmAccountId: {0}", CrmAccountId),ModuleTraceSwitch.Sw.Info);
                    im.AddCustomerProperty(CrmStr.parentcustomerid, CrmStr.account, CrmAccountId);
                }
                im.jobtitle             =   RadTjobtitle.Text.Trim();
                im.donotsendmm          =   ChkRDMarketing.Checked;
                im.mobilephone          =   RadTmobilephone.Text.Trim();

                // Create in CRM using web service
                try
                {
                    Guid ContactID      = im.adminCreate();
                    if (ModuleTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmInputContact CrmInputContact_ADNUpdateModule Contact created contactid: {0}", ContactID),ModuleTraceSwitch.Sw.Info);
                }
                catch (Exception ex)
                {
                    if (ModuleTraceSwitch.Sw.TraceError)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CrmInputContact CrmInputContact_ADNUpdateModule Adding Contact ex :{0}", ex),ModuleTraceSwitch.Sw.Info);
                    throw;
                }

                // Assign to default owner
                if ( Settings[AStr.AssignToOwner].ToBool() )
                {
                    try
                    {
                        string str = Settings[AStr.CrmInputContactOwner].Value;
                        if (ModuleTraceSwitch.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmInputContact CrmInputContact_ADNUpdateModule  assigning contact to owner id: '{0}'", str),ModuleTraceSwitch.Sw.Info);
                        im.adminAssign(new Guid(str));
                        if (ModuleTraceSwitch.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmInputContact CrmInputContact_ADNUpdateModule contact assigned to owner id: '{0}'", str),ModuleTraceSwitch.Sw.Info);
                    }
                    catch (Exception ex)
                    {
                        if (ModuleTraceSwitch.Sw.TraceError)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CrmInputContact CrmInputContact_ADNUpdateModule assigning contact ex :{0}", ex),ModuleTraceSwitch.Sw.Info);
                        throw;
                    }
                }
                clean();
            }
            catch (Exception ex)
            {
                if (ModuleTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"CrmInputContact CrmInputContact_ADNUpdateModule ex :{0}", ex),ModuleTraceSwitch.Sw.Info);
                throw;
            }
        }
        
        
        /// <summary>
        /// clean : re-initialized fields 
        /// </summary>
        protected void clean()
        {
            RadtxtPseudo.Text           = string.Empty;
            RadtxtFirstname.Text        = string.Empty;
            RadtxtLastname.Text         = string.Empty;
            RadtxtEmailaddress1.Text    = string.Empty;
            RadtxtAddress1_line1.Text   = string.Empty;
            RadtxtAddress1_city.Text    = string.Empty;
            RadtxtAddress1_country.Text = string.Empty;
            RadtxtAddress1_county.Text  = string.Empty;
            RadtxtAddress1_postalcode.Text  = string.Empty;
            RadtxtAddress1_telephone1.Text  = string.Empty;
            RadtxtFax.Text              = string.Empty;
            RadtxtCompanyName.Text      = string.Empty;
            Radtxtaddress1_line2.Text   = string.Empty;
            RadTjobtitle.Text           = string.Empty;
            RadTmobilephone.Text        = string.Empty;
            ChkRDMarketing.Checked      = false;
        }

        public override void Page_PreInit(object sender, EventArgs e)
        {
            updateBtn.SkinID    =   "Update_" + Helpers.LocalizeHelper.GetCurrentNeutralCultureName();
            ResetBtn.SkinID     =   "Reset_" + Helpers.LocalizeHelper.GetCurrentNeutralCultureName();
            base.Page_PreInit(sender, e);
        }

        /// <summary>
        /// Reset the listbox to values from the fields grid
        /// </summary>
        void ResetBtn_Click(object sender, ImageClickEventArgs e)
        {
            clean();
        }

        #region Std overrides

        override protected void OnInit(EventArgs e)
        {
            InitializeComponent();
            base.OnInit(e);
        }

        private void InitializeComponent()
        {
            Load            +=  new System.EventHandler(this.Page_Load);
            ADNUpdateModule +=  new PortalModuleEventHandler(CrmInputContact_ADNUpdateModule);
            ResetBtn.Click  +=  new ImageClickEventHandler(ResetBtn_Click);
        }
        
        #endregion Std overrides
    }
}
